﻿// -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	SmartLib
//  File name:	EventLogLogger.cs
//  Developer:	Igor Solomatov
//  Created:	04.11.2012
// 
// -------------------- iSharePoint -------------------- //

using System;
using System.Diagnostics;

namespace Smart.Loggers
{
	public class EventLogProvider : ILoggerProvider
	{
		/// <summary>
		/// The higher the value, the most important provider is
		/// </summary>
		public int Priority { get { return 100; } }

		/// <summary>
		/// Minimal severity to log
		/// </summary>
		public MessageSeverity MinimalSeverity { get { return MessageSeverity.Error; } }

		/// <summary>
		/// Source for EventLog in Application journal
		/// </summary>
		public string Source { get; set; }

		public EventLogProvider(string source)
		{
			Source = source;
		}

		[ThreadStatic]
		private static EventLog _eventLog;

		/// <summary>
		/// Returns event log
		/// </summary>
		public EventLog GetEventLog()
		{
			var eventLog = _eventLog;

			if (eventLog != null)
				return eventLog;

			if (!EventLog.SourceExists(Source))
				EventLog.CreateEventSource(Source, "Application");

			return _eventLog = new EventLog { Source = Source };
		}

		/// <summary>
		/// Log function
		/// </summary>
		public void Log(string category, MessageSeverity severity, string module, string message, Exception x, string fullMessage)
		{
			try
			{
				EventLogEntryType type;

				switch (severity)
				{
					case MessageSeverity.None:
					case MessageSeverity.Info:
					case MessageSeverity.Trace:
						type = EventLogEntryType.Information;
						break;

					case MessageSeverity.Important:
						type = EventLogEntryType.Warning;
						break;

					case MessageSeverity.Error:
						type = EventLogEntryType.Error;
						break;

					default:
						throw new ArgumentOutOfRangeException("severity");
				}

				var log = GetEventLog();

				log.WriteEntry(fullMessage, type);
			}
			catch (Exception ix)
			{
				Trace.WriteLine("EventLogProvider.Log." + ix.GetType().Name + ": failed to write EventLog entry, " + ix.Message);
			}
		}
	}
}